package com.neu.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.neu.entity.Admin;
import com.neu.exception.CustomException;
import com.neu.service.AdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);
    @Autowired
    private AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
//        if(HttpMethod.OPTIONS.toString().equals(request.getMethod())){
//            log.info("这是OPTIONS的请求方法，直接放行");
//            return true;
//        }

        //1.从HTTP请求的headers中获取token
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)){
            //如果没拿到，我再去参数里面拿一波试试  URL地址栏上传的参数
            token = request.getParameter("token");
        }
        //2.开始执行认证
        if(StrUtil.isBlank(token)){
            throw new CustomException("无token，请重新登录");
        }
        //获取token中的userId  token中只有用户ID，password是秘钥
        String userId;
        Admin admin;
        try{
            userId = JWT.decode(token).getAudience().get(0);
            //根据token中的userId查询数据库
            admin = adminService.findById(Integer.parseInt(userId));
        }catch (Exception e){
            String errMsg = "token验证失败，请重新登录";
            log.error(errMsg + ",token = "+ token,e);
            throw new CustomException(errMsg);
        }
        if(admin == null){
            throw new CustomException("用户不存在，请重新登录");
        }
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();
            jwtVerifier.verify(token);
        }catch (JWTVerificationException e){
            throw new CustomException("token验证失败，请重新登录");
        }
        return true;


    }
}
